from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe as ms

from accounts.models import *
from accounts.fields import *

class SignupForm(forms.Form):
        
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = UsernameField()
    password = forms.CharField(min_length=6, widget=forms.PasswordInput)
    confirm_password = forms.CharField(min_length=6, widget=forms.PasswordInput)
    name = forms.CharField(max_length=50, label=u'Company / Organization')
    label = AccountLabelField(label=ms(u'Subdomain'), help_text=u"This cannot be changed later.")
    domain = forms.ChoiceField(choices=settings.ACCOUNT_SUBDOMAIN_CHOICES)
    plan = RatePlanField()
    terms_of_service = forms.BooleanField(initial=False, error_messages={'required':'You must agree to the terms of service.'})
    heard_from = forms.ChoiceField(label=u'How did you hear about us?', choices=settings.ACCOUNT_ADVERTISING_CHOICES, required=False)
    referrer = forms.CharField(required=False, widget=forms.HiddenInput())
    
    def __init__(self, *args, **kwargs):
        initial = kwargs.pop('initial', {})
        if 'referrer' in initial:
            referrer_code = initial.get('referrer')
            try:
                account = Account.objects.get(status=Account.ACTIVE, referrer_code=referrer_code)
                initial.update({'referrer':referrer_code})
            except Account.DoesNotExist:
                try:
                    account = Account.objects.get(status=Account.ACTIVE, label=referrer_code)
                    initial.update({'referrer':account.referrer_code})
                except Account.DoesNotExist:
                    initial.update({'referrer':''})         
        kwargs.update({'initial':initial})
        super(SignupForm, self).__init__(*args, **kwargs)
        
    def clean_referrer(self):
        try:
            account = Account.objects.get(status=Account.ACTIVE, referrer_code=self.cleaned_data['referrer'])
            return  account
        except Account.DoesNotExist:
            return None
            
    def clean_label(self):
        return self.cleaned_data['label'].lower()
    
    def save(self):
        account = Account.objects.create_new_account(**self.cleaned_data)
        account.owner.send_welcome_email()
        return account
    